<?php  

/**
* Library of the general functions
* Библиотека общих функций
* @author IT studio IRBIS-team
* @copyright © 2009 IRBIS-team
*/
/////////////////////////////////////////////////////////
 
/**
* Generation of page of an error at access out of system
* Генерация страницы ошибки при доступе вне системы
*/
    if(!defined('IRB_KEY'))
    {
       header("HTTP/1.1 404 Not Found");      
       exit(file_get_contents('../404.html'));
    }        
/////////////////////////////////////////////////////////
     
/**  
* Function of formation of GET-parametres  
* Функция формирования GET-параметров  
*/   
   function href() 
   { 
       global $GET;   
       $tmp = $GET;    
       $href = ''; 
        
       $arg = func_get_args();
	   		 		
       if(is_array($arg[0]))
           $arg = $arg[0];     

       if(defined('IRB_ADMIN'))
           $host = IRB_HOST .'admin/';
       else
	       $host = IRB_HOST;      
	   
	   if($arg[0] == 'host') 
           return IRB_HOST . $href; 
                     
        foreach($arg as $var)    
        { 
            $param = explode('=', $var);  
             
            if(array_key_exists($param[0], $tmp)) 
                $tmp[$param[0]] = $param[1];   
            else 
                die('The variable <b>'. $param[0] .'</b> is not defined');   
        } 
		
        $cnt = array_flip(array_keys($tmp));
        $tmp = array_slice($tmp, 0, $cnt[$param[0]] + 1);  
		       
        foreach($tmp as $var => $val)  
           if(IRB_REWRITE == 'on')  
              $href .= '/'. $val;        
           elseif(!empty($val)) 
              $href .= '&'. $var .'='. $val; 
                   
            
       if(IRB_REWRITE == 'on') 
           return $host . trim($href, '/0'); 
       else 
           return $host .'?'. trim($href, '&');        
   }

/**
* Function of Redirections
* Функция перенаправления
*/     
   function reDirect()
   {  
        $arguments = func_get_args();
           
        if(count($arguments))
        {                            
            header('location: '. href($arguments));
            exit();
        }
        else
        {
            header('location: '. str_replace("/index.php", "", $_SERVER['HTTP_REFERER']));
            exit();
        }        
   } 


/**
* Information conclusion
* Вывод информации        
*/  
    function getInfo($info)
    {
        if(count($info))
			{
			$i_string ='';
			foreach($info as $i_key => $i)
				$i_string .= "<p>".$i."</p>";
				
            return $i;
			}
        else
            return '&nbsp;';
    }    
   
	    
/**
* Active links
* Активные ссылки        
*/    
    function active($page)
    {
       global $GET;
	    if($GET['page'] == $page)
            return 'class="active"';
    }     
   
/**
* Функция перевода даты из азиатского формата в прописной
* Translation function of date from the Asian format in the string
* @param string $date, boolean $format
* @return string
*/
    function formatDate($date, $format = true) 
    { 
        global $month;

        $day  = substr($date, 8, 2);         
        $mnt  = $month[substr($date, 5, 2)];        
        $year = substr($date, 0, 4); 
        $time = '';
		
        if($format)         
            $time = ' '. substr($date, 11); 

        return $day .' '. $mnt .' '. $year . $time; 
    }
    
/** 
* Return of checkbocses    
* Возврат чекбоксов 
*/ 
    function returnCheck($id, $return) 
    { 
       return ($id == $return)?'checked="checked"':NULL; 
    } 	

/** 
* Countries array    
* Массив стран
*/ 
    function getCountries() 
	{ 
		include_once './libs/mysql.php'; 
		$query = mysqlQuery("SELECT c.country_id,c.name as country_name FROM country c");
		
		if(mysql_num_rows($query) > 0)
			{
			while($row = mysql_fetch_assoc($query))
				$arr_country[] = $row;
			}
		
		if(!empty($arr_country))
			return $arr_country; 
		else 
			return 0;
    } 
/** 
* Available domains array to user
* Доступные пользователю домены
*/ 
    function getDomsOfUser($user_id, $role=1) 
	{ 
		if(empty($user_id)) exit;
		
		include_once './libs/mysql.php'; 
		
		$query = mysqlQuery("SELECT 
									sd.id as d_id, sd.caption as d_caption 
								FROM 
									`". IRB_DBPREFIX ."domains` sd
								WHERE 
									sd.id IN 
									
									(SELECT 
											sdlu.domain_id 
										FROM 
											`". IRB_DBPREFIX ."dom_link_user` sdlu
										WHERE 
											sdlu.user_id = '".$user_id."'
										AND 
											sdlu.role >= '".$role."')
							");
		
		if(mysql_num_rows($query) > 0)
			{
			while($row = mysql_fetch_assoc($query))
				$arr_doms[] = $row;
			return $arr_doms;
			}
			
		return 0;
    } 	
/** 
* Available domains of asset
* Указанные домены данного актива
*/ 
function getDomsOfAsset($asset_id)
{
	if(empty($asset_id)) exit;
	include_once './libs/mysql.php';
	
	$query = mysqlQuery("SELECT 
								sd.id as d_id, sd.caption as d_caption
							FROM 
								`". IRB_DBPREFIX ."domains` sd
							WHERE 
								sd.id IN
							
								(SELECT 
										saldu.dom_id as d_id
									FROM 
										`". IRB_DBPREFIX ."asset_link_dom_user` saldu							
									WHERE 
										saldu.asset_id = '". $asset_id ."')");	
	
	if(mysql_num_rows($query) > 0)
	{
		while($row = mysql_fetch_assoc($query))
			$d_a[] = $row;
			
		return $d_a;
	}
	
	return 0;
}

/** 
* Available domains of request
* Указанные домены данной заявки
*/ 
function getDomsOfRequest($request_id)
{
	if(empty($request_id)) exit;
	include_once './libs/mysql.php';
	
	$query = mysqlQuery("SELECT 
								sd.id as d_id, sd.caption as d_caption
							FROM 
								`". IRB_DBPREFIX ."domains` sd
							WHERE 
								sd.id IN
								
								(SELECT 
										srldu.dom_id as d_id
									FROM 
										`". IRB_DBPREFIX ."requests_link_dom_user` srldu							
									WHERE 
										srldu.request_id = '". $request_id ."')
						");	
	
	if(mysql_num_rows($query) > 0)
	{
		while($row = mysql_fetch_assoc($query))
			$d_a[] = $row;
			
		return $d_a;
	}
	
	return 0;
}

/** 
* Number invites
* Количество приглашений пользователя
*/ 
function getNumInvites($user_id)
{
	if(!empty($user_id))
	{
		$query = mysqlQuery("SELECT COUNT(*) as num
							FROM
								`". IRB_DBPREFIX ."dom_invites` di
							WHERE
								di.user_id = '".$user_id."'
							AND
								di.accept_status = 'none'");
		$inv = mysql_fetch_assoc($query);
		return $inv['num'];
	}
}
/** 
* Random string    
* Рандомный набор символов
*/ 
function genHash($length = 8){
   $chars = 'abdefhiknrstyzABDEFGHKNQRSTYZ23456789';
   $numChars = strlen($chars);
   $string = '';
   for ($i = 0; $i < $length; $i++) {
     $string .= substr($chars, rand(1, $numChars) - 1, 1);
   }
   return md5($string);
}
		